package logic

import (
	"context"
	"errors"
	"regi-sys/cache"
	"regi-sys/model"

	"regi-sys/userrpc/internal/svc"
	"regi-sys/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user model.User
	result, _ := cache.Rdb.Get(cache.Ctx, "captchaCode_"+in.Account).Result()
	if result != in.Captcha {
		return nil, errors.New("验证码错误")
	}
	err := user.UserDetailByAccount(model.DB, in.Account)
	if err != nil {
		user = model.User{
			Account:  in.Account,
			Password: in.Password,
		}
		err = user.UserAdd(model.DB)
		if err != nil {
			return nil, errors.New("创建失败")
		}
	}
	cache.Rdb.Del(cache.Ctx, "captchaCode_"+in.Account)

	return &userrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
